class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.
        
        :type root: TreeNode
        :rtype: str
        """
        tree = []
        def encode(cur):
            if not cur:
                tree.append('#')
            else:
                tree.append(str(cur.val))
                encode(cur.left)
                encode(cur.right)
        encode(root)
        return ' '.join(tree)    

    def deserialize(self, data):
        """Decodes your encoded data to tree.
        
        :type data: str
        :rtype: TreeNode
        """
        vals = iter(data.split())
        def decode():
            val = next(vals)
            if val == '#':
                return None
            else:
                cur = TreeNode(int(val))
                cur.left = decode()
                cur.right = decode()
            return cur

        return decode()